package com.shop.shoporder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.shop.shoporder.common.MessageConstants;
import com.shop.shoporder.common.InterfaceVer;
import com.shop.shoporder.common.Response;
import com.shop.shoporder.entity.GroupbuyGoodInfo;
import com.shop.shoporder.entity.Spec;
import com.shop.shoporder.entity.order.*;
import com.shop.shoporder.mapper.GroupbuyGoodMapper;
import com.shop.shoporder.mapper.order.*;
import com.shop.shoporder.service.CartService;
import com.shop.shoporder.service.OrderService;
import com.shop.shoporder.service.UserNoService;
import lombok.Synchronized;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    UserAddressMapper userAddressMapper;
    @Autowired
    OrderAddressMapper orderAddressMapper;
    @Autowired
    FreightMapper freightMapper;
    @Autowired
    UserNoService userNoService;
    @Autowired
    CartService cartService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    LimitAreaMapper limitAreaMapper;
    @Autowired
    GroupbuyGoodMapper groupbuyGoodMapper;
    @Override
    public int deleteByPrimaryKey(Integer orderId) {
        return orderMapper.deleteByPrimaryKey(orderId);
    }

    @Override
    public int insert(Order record) {
        return orderMapper.insert(record);
    }

    @Override
    public int updatePayType(Integer payType, String orderNo) {
        return orderMapper.updatePayType(payType,orderNo);
    }

    @Override
    public int insertSelective(Order record) {
        return orderMapper.insertSelective(record);
    }

    @Override
    public Order selectByPrimaryKey(Integer orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public int updateByPrimaryKeySelective(Order record) {
        return orderMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Order record) {
        return orderMapper.updateByPrimaryKey(record);
    }


    @Transactional
    @Override
    public synchronized Response addOrder(Map<String, String> map, HttpServletRequest request) throws Exception {
        Order order=new Order();
        String cartsTemp="";
        List<String> cartidsList=new ArrayList<>();
        Integer addressId=0;
        Double coupon=0.00;
        Double cashcoupon=0.00;
        Double freight=0.00;
        int userNoId = 0;
        int type=0;
        List<CartList> cartListList=new ArrayList<>();
        double orderMoney=0;
        double avgCoupon=0;
        double avgCashCoupon=0;

        int activity500=0;
        int activity600=0;
        int sumLimit500=0;
        int sumLimit600=0;
        int productCount=0;
        int activity=0;
        int sumLimit=0;
        int guigeId=0;
        int goodsId=0;
        int monthLimit28=0;
        int provinceId=0;
        int supplierNoId=-1;
        int sumType=0;
        int oneType=0;
        double buyonePrice=0;
        double groupByPrice=0;
        String groupType="0";
        double groupPrice=0;
        int groupBuyGoodsId=0;
        int groupbuyId=0;
        int participateId=0;
        if(map!=null){
            try {groupBuyGoodsId=Integer.parseInt(map.get("groupBuyGoodsId"));}catch (Exception e){}
            try {groupbuyId=Integer.parseInt(map.get("groupbuyId"));}catch (Exception e){}
            try {participateId=Integer.parseInt(map.get("participateId"));}catch (Exception e){}
            cartsTemp=map.get("cartIds")==null?"":map.get("cartIds");
            addressId= InterfaceVer.VerNumber(map.get("addressId"));
            coupon= InterfaceVer.VerDoubleNumber(map.get("coupon"));
            cashcoupon= InterfaceVer.VerDoubleNumber(map.get("cashCoupon"));
            freight= InterfaceVer.VerDoubleNumber(map.get("freight"));
            if(!cartsTemp.equals("")){
                cartidsList=JSON.parseArray("["+cartsTemp+"]",String.class);
            }
            userNoId = InterfaceVer.VerNumber(map.get("userNoId"));
            //地址相关判断
            UserAddress address=userAddressMapper.selectByPrimaryKey(addressId);
            OrderAddress orderAddress = new OrderAddress();
            if(address!=null) {
                provinceId=address.getProvinceId();
                orderAddress.setProvinceId(address.getProvinceId());
                orderAddress.setCityId(address.getCityId());
                orderAddress.setUserNoId(address.getUserNoId());
                orderAddress.setAreaId(address.getAreaId());
                orderAddress.setName(address.getName());
                orderAddress.setPhone(address.getPhone());
                orderAddress.setDetailAddr(address.getDetailAddr());
                orderAddress.setIsDelete(0);
            }
            if((address.getPhone()==null?"":address.getPhone()).equals("")){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"失败,手机号有误!",request);
            }
            if((address.getName()==null?"":address.getName()).equals("")){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"失败,收货姓名有误!",request);
            }
            if((address.getDetailAddr()==null?"":address.getDetailAddr()).equals("")){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"失败,详细地址有误!",request);
            }
            int orderAddressId=0,reso1=0;
            if(orderAddress!=null&&(orderAddress.getUserNoId()==null?0:orderAddress.getUserNoId())>0) {
                reso1 = orderAddressMapper.insert(orderAddress);
            }
            if (reso1 > 0) {
                orderAddressId=orderAddress.getId();
            }
            if(orderAddressId<=0){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"订单生成失败,地址不正确!",request);
            }
            //地址相关判断结束

            if(cartidsList!=null&&cartidsList.size()>0){
                cartListList=cartMapper.selectCartListSureOrder(userNoId,cartidsList);
                if(cartListList!=null&&cartListList.size()>0){
                    for (CartList cartList:cartListList) {
                        for (Carts carts:cartList.getCartsList()) {
                            guigeId=carts.getGuigeId()==null?0:carts.getGuigeId();//规格ID
                            goodsId=carts.getProductId()==null?0:carts.getProductId();

                            //团购
                            //0正常购买、1土豪购、2拼团
                            groupType=carts.getRemark2()==null?"0":carts.getRemark2();
                            if(groupType.equals("1")){
                                GroupbuyGoodInfo groupbuyGoodInfo =groupbuyGoodMapper.getGoodInfoByGoodIdAndSpecId(goodsId,guigeId);
                                if(groupbuyGoodInfo!=null){
                                    groupPrice=groupbuyGoodInfo.getBuyonePrice()==null?0:groupbuyGoodInfo.getBuyonePrice();
                                }
                            }
                            if(groupType.equals("2")){
                                GroupbuyGoodInfo groupbuyGoodInfo =groupbuyGoodMapper.getGoodInfoByGoodIdAndSpecId(goodsId,guigeId);
                                if(groupbuyGoodInfo!=null){
                                    groupPrice=groupbuyGoodInfo.getGroupbyPrice()==null?0:groupbuyGoodInfo.getGroupbyPrice();
                                }
                            }

                            supplierNoId=carts.getSupplierNoId()==null?-1:carts.getSupplierNoId();
                            LimitArea limitArea=limitAreaMapper.selectBySupplierId(supplierNoId);
                            if(limitArea!=null) {
                                String limitAreas = limitArea.getLimitAreas() == null ? "" : limitArea.getLimitAreas();
                                String guigeName = carts.getGuigeName() == null ? "" : carts.getGuigeName();
                                if (checkArea(provinceId + "", limitAreas)) {
                                    return new Response(MessageConstants.MSG_ADD_FAILED, null, 0, "失败,该产品" + guigeName + "当前地址不发货!", request);
                                }
                            }

                            productCount=carts.getProductCount()==null?0:carts.getProductCount();
                            int cartStatus=carts.getCartStatus()==null?501:carts.getCartStatus();
                            int oneLimitActivity=carts.getuLimit()==null?0:carts.getuLimit();
                            int sumLimitActivity=carts.getSumLimit()==null?0:carts.getSumLimit();
                            //活动产品限量
                            //new
                            LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
                            if(lettuceConnectionFactory != null){
                                lettuceConnectionFactory.setDatabase(15);
                                redisTemplate.setConnectionFactory(lettuceConnectionFactory);
                                lettuceConnectionFactory.resetConnection();
                            }

                            Object object= redisTemplate.opsForValue().get("activity"+guigeId);
                            activity=InterfaceVer.VerNumber(object==null?"0":(int)object+"");

                            if(oneLimitActivity>0){
                                oneType=1;
                                Object oneLimit=redisTemplate.opsForValue().get("oneLimit"+userNoId+guigeId);
                                int oneLimitInt=InterfaceVer.VerNumber(oneLimit==null?"0":(int)oneLimit+"");
                                if((oneLimitInt+productCount)>oneLimitActivity){
                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"产品限量"+oneLimitActivity,request);
                                }
                            }
                            if(sumLimitActivity>0){
                                sumType=1;
                                Object OBsumLimit= redisTemplate.opsForValue().get("sumLimit"+guigeId);
                                sumLimit=InterfaceVer.VerNumber(OBsumLimit==null?"0":(int)OBsumLimit+"");
                                //System.out.println("---->"+sumLimit);
                                if(sumLimit<=0){
                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"活动结束!",request);
                                }
                            }
//                            else {
//                                if((oneLimitInt+productCount)>oneLimitActivity){
//                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"产品限量"+oneLimitActivity,request);
//                                }
//                            }
                            if(activity==guigeId){
                                //28抢购 每个月只能抢购一个产品且购买数量只能为1
                                JSONObject jsonObject=userNoService.getUserNo(userNoId);
                                if(jsonObject!=null){
                                    //rankId InterfaceVer.VerDoubleNumber(jsonObject.get("balance1") == null ? "" : jsonObject.get("balance1").toString());
                                    int rankId = InterfaceVer.VerNumber(jsonObject.get("rankId") == null ? "" : jsonObject.get("rankId").toString());
                                    monthLimit28=InterfaceVer.VerNumber(jsonObject.get("monthLimit28") == null ? "" : jsonObject.get("monthLimit28").toString());
                                    if(rankId==1||rankId==2){

                                    }else {
                                        return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"店主不能参与抢购!",request);
                                    }
                                }else {
                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"用户信息有误!",request);
                                }

                                Object monthLimit=redisTemplate.opsForValue().get("monthLimit"+userNoId);
                                int monthLimitInt=InterfaceVer.VerNumber(monthLimit==null?"0":(int)monthLimit+"");
                                if(monthLimitInt==1){
                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"每月限抢购一次",request);
                                }
                                //店主以下会员免费抢购只能抢两次
                                Object monthLimitAll=redisTemplate.opsForValue().get("monthLimitAll"+userNoId);
                                int monthLimitAllInt=InterfaceVer.VerNumber(monthLimitAll==null?"0":(int)monthLimitAll+"");
                                if(monthLimitAllInt==0){//没有缓存从数据库获取
                                    monthLimitAllInt=monthLimit28;
                                }
                                if(monthLimitAllInt==2){
                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"抢购活动限参与两次",request);
                                }
//                                if((oneLimitInt+productCount)>oneLimitActivity){
//                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"产品限量"+oneLimitActivity,request);
//                                }
                                //int activity=carts.getSumLimit()==null?0:carts.getSumLimit();//规格总购买限量
//                                Object OBsumLimit= redisTemplate.opsForValue().get("sumLimit"+guigeId);
//                                sumLimit=InterfaceVer.VerNumber(OBsumLimit==null?"0":(int)OBsumLimit+"");
//                                //System.out.println("---->"+sumLimit);
//                                if(sumLimit<=0){
//                                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"活动结束!",request);
//                                }
                                type=1;
                            }
                            //new
                            //活动产品限量
                            if(cartStatus==501) {
                                if(groupType.equals("0")) {//正常下单
                                    orderMoney += (carts.getPrice() == null ? 0 : carts.getPrice()) * productCount;
                                }else {//团购
                                    orderMoney += groupPrice * productCount;
                                }
                                avgCoupon += (carts.getCoupon() == null ? 0 : carts.getCoupon()) * productCount;
                                avgCashCoupon += (carts.getVouchers() == null ? 0 : carts.getVouchers()) * productCount;
                            }else {
                                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"购物车已经生成!",request);
                            }
                        }
                    }
                }else{
                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"购物车已经生成",request);
                }
            }else {
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"购物车数据有误!",request);
            }
            if(orderMoney<=0){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"生成失败,商品金额数据有误!",request);
            }

            order.setAddressId(orderAddressId);//地址id
            java.text.DateFormat format2 = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
            String orderString = format2.format(new Date());
            int intRandom=(int)(1+Math.random()*(10-1+1)*1000);
            String OrderNo="D"+orderString+intRandom;
            order.setOrderNo(OrderNo);
            order.setOrderMoney(orderMoney);
            order.setAvaCoupon(avgCoupon);
            order.setAvaCashcoupon(avgCashCoupon);
            order.setUsernoId(userNoId);
            order.setCoupon(coupon);
            order.setCashCoupon(cashcoupon);
            order.setFreight(freight);
            order.setGroupbuyGoodsid(groupBuyGoodsId);
            order.setGroupbuyId(groupbuyId);
            order.setParticipateId(participateId);
            int res=orderMapper.insertSelective(order);
            if(res>0){
                Integer res1=cartMapper.upCartStatus(OrderNo,cartidsList);//更新购物车的状态
                if(res1>=0) {
                    if(type==1) {
//                        sumLimit=sumLimit-1;
//                        redisTemplate.opsForValue().set("sumLimit" + guigeId, sumLimit);
//                        redisTemplate.opsForValue().set("oneLimit" + userNoId + activity, productCount);
                        //28抢购 每个月只能抢购一个产品且购买数量只能为1
                        redisTemplate.opsForValue().set("monthLimit" + userNoId, 1);
                        //店主以下会员免费抢购只能抢两次
                        Object monthLimitAll = redisTemplate.opsForValue().get("monthLimitAll" + userNoId);
                        int monthLimitAllInt = InterfaceVer.VerNumber(monthLimitAll == null ? "0" : (int) monthLimitAll + "");
                        int lastNumber = monthLimitAllInt + 1;
                        redisTemplate.opsForValue().set("monthLimitAll" + userNoId, lastNumber);
                    }
                    if(oneType==1){
                        redisTemplate.opsForValue().set("oneLimit" + userNoId + activity, productCount);
                    }
                    if(sumType==1){
                        sumLimit=sumLimit-1;
                        redisTemplate.opsForValue().set("sumLimit" + guigeId, sumLimit);
                    }
                    return new Response(MessageConstants.MSG_SUCCESS, order.getOrderNo(), 1, "订单生成成功!", request);
                }else {
                 throw new RuntimeException();
                }
            }else {
                throw new RuntimeException();
                //return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"订单生成失败!",request);
            }
        }
        return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"订单生成失败!",request);
    }

    @Override
    public Order selectByOrderNo(String orderNo) {
        return orderMapper.selectByOrderNo(orderNo);
    }

    @Override
    public Order selectByOrderNoAsDetails(String orderNo) {
        return orderMapper.selectByOrderNoAsDetails(orderNo);
    }

    @Override
    public List<Order> adminSelectOrderList(Map<String, String> map, HttpServletRequest request) {
        int usernoId=0;
        int orderStatus=0;
        String orderNo="";
        String logName="";
        String phone="";
        List<Order> list=new ArrayList<>();
        Set<String> userNoIds=new HashSet<>();
        if(map!=null) {
            usernoId=InterfaceVer.VerNumber(map.get("usernoId"));
            orderStatus=InterfaceVer.VerNumber(map.get("orderStatus"));
            orderNo=InterfaceVer.VerStr(map.get("orderNo"));
            logName=InterfaceVer.VerStr(map.get("logName"));
            phone=InterfaceVer.VerStr(map.get("phone"));
            System.out.println("usernoId:"+usernoId+" orderStatus:"+orderStatus+" orderNo:"+orderNo+" logName:"+logName+" phone:"+phone);
            list=orderMapper.adminSelectOrderList(orderStatus,orderNo,usernoId,logName,phone);
            if(list!=null&&list.size()>0){
                for (Order order:list) {

                    String userNoIdStr=order.getUsernoId()==null?"":order.getUsernoId()+"";
                    if(!"".equals(userNoIdStr)){
                        userNoIds.add(userNoIdStr);
                    }
                }
                List<String> userNoIdsList = new ArrayList<>(userNoIds);
                String noList=org.apache.commons.lang.StringUtils.join(userNoIdsList.toArray(),",");
                List<UserNo> jsonObject1 = userNoService.getUserNoList(noList);
                if (jsonObject1 != null&&jsonObject1.size()>0) {
                    for (UserNo userNo:jsonObject1) {
                        int userNoId=userNo.getId();
                        String userNoStr=userNo.getNo();
                        //System.out.println("userNoId:"+userNoId+" userNoStr:"+userNoStr);
                        for (Order order:list) {
                            if(order.getUsernoId()==userNoId){
                                order.setUsernoName(userNoStr);
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Order> adminSelectOrderShopList(Map<String, String> map, HttpServletRequest request) {
        int usernoId=0;
        int orderStatus=0;
        int zoneId=0;
        String orderNo="";
        String logName="";
        String phone="";
        List<Order> list=new ArrayList<>();
        Set<String> userNoIds=new HashSet<>();
        if(map!=null) {
            usernoId=InterfaceVer.VerNumber(map.get("usernoId"));
            zoneId=InterfaceVer.VerNumber(map.get("zoneId"));
            orderStatus=InterfaceVer.VerNumber(map.get("orderStatus"));
            orderNo=InterfaceVer.VerStr(map.get("orderNo"));
            logName=InterfaceVer.VerStr(map.get("logName"));
            phone=InterfaceVer.VerStr(map.get("phone"));
            System.out.println("usernoId:"+usernoId+" orderStatus:"+orderStatus+" orderNo:"+orderNo+" logName:"+logName+" phone:"+phone+" zoneId:"+zoneId);
            list=orderMapper.adminSelectOrderShopList(orderStatus,orderNo,usernoId,logName,phone,zoneId);
            if(list!=null&&list.size()>0){
                for (Order order:list) {
                    String userNoIdStr=order.getUsernoId()==null?"":order.getUsernoId()+"";
                    if(!"".equals(userNoIdStr)){
                        userNoIds.add(userNoIdStr);
                    }
                }
                List<String> userNoIdsList = new ArrayList<>(userNoIds);
                String noList=org.apache.commons.lang.StringUtils.join(userNoIdsList.toArray(),",");
                List<UserNo> jsonObject1 = userNoService.getUserNoList(noList);
                if (jsonObject1 != null&&jsonObject1.size()>0) {
                    for (UserNo userNo:jsonObject1) {
                        int userNoId=userNo.getId();
                        String userNoStr=userNo.getNo();
                        //System.out.println("userNoId:"+userNoId+" userNoStr:"+userNoStr);
                        for (Order order:list) {
                            if(order.getUsernoId()==userNoId){
                                order.setUsernoName(userNoStr);
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Order> adminSelectOrderList1(Map<String, String> map, HttpServletRequest request) {
        int usernoId=0;
        int orderStatus=0;
        String orderNo="";
        String logName="";
        String phone="";
        List<Order> list=new ArrayList<>();
        Set<String> userNoIds=new HashSet<>();
        if(map!=null) {
            usernoId=InterfaceVer.VerNumber(map.get("usernoId"));
            orderStatus=InterfaceVer.VerNumber(map.get("orderStatus"));
            orderNo=InterfaceVer.VerStr(map.get("orderNo"));
            logName=InterfaceVer.VerStr(map.get("logName"));
            phone=InterfaceVer.VerStr(map.get("phone"));
            System.out.println("usernoId:"+usernoId+" orderStatus:"+orderStatus+" orderNo:"+orderNo+" logName:"+logName+" phone:"+phone);
            list=orderMapper.adminSelectOrderList1(orderStatus,orderNo,usernoId,logName,phone);
            if(list!=null&&list.size()>0){
                for (Order order:list) {
                    String userNoIdStr=order.getUsernoId()==null?"":order.getUsernoId()+"";
                    if(!"".equals(userNoIdStr)){
                        userNoIds.add(userNoIdStr);
                    }
                }
                List<String> userNoIdsList = new ArrayList<>(userNoIds);
                String noList=org.apache.commons.lang.StringUtils.join(userNoIdsList.toArray(),",");
                List<UserNo> jsonObject1 = userNoService.getUserNoList(noList);
                if (jsonObject1 != null&&jsonObject1.size()>0) {
                    for (UserNo userNo:jsonObject1) {
                        int userNoId=userNo.getId();
                        String userNoStr=userNo.getNo();
                        //System.out.println("userNoId:"+userNoId+" userNoStr:"+userNoStr);
                        for (Order order:list) {
                            if(order.getUsernoId()==userNoId){
                                order.setUsernoName(userNoStr);
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    @Override
    public int updateOrderStatus1(String orderStatus, Date deliveryTime, List<String> orderList) {
        return orderMapper.updateOrderStatus1(orderStatus,deliveryTime,orderList);
    }

    public Boolean checkArea(String provinceId, String areaIds) {
        boolean bools=false;
        String []strs=areaIds.split(",");
        for (String str:strs){
            if(str.equals(provinceId)){
                bools=true;
                break;
            }
        }
        return bools;
    }
    @Override
    public List<Order> selectOrderNumber(Map<String, String> map, HttpServletRequest request) {
        int usernoId=0;
        List<Order> orderList=new ArrayList<>();
        String orserStatusStr="701,702,703,704,705,706,707";
        List<Order> list=new ArrayList<>();
        for (String str: orserStatusStr.split(",")) {
            list.add(new Order(0,str));
        }
        if(map!=null) {
            usernoId = InterfaceVer.VerNumber(map.get("userNoId"));
            orderList=orderMapper.selectOrderNumber(usernoId);
            for (Order order:list) {
                for (Order order1:orderList) {
                    if(order.getOrderStatus().equals(order1.getOrderStatus())){
                        order.setNumber(order1.getNumber());
                    }
                }
            }

        }
        return list;
    }

    @Transactional
    @Override
    public Response cancelOrder(Map<String, String> map, HttpServletRequest request) throws Exception {
        int userNoId=0;
        String orderNo="";
        Order order=new Order();
        if(map!=null) {
            userNoId = InterfaceVer.VerNumber(map.get("userNoId"));
            orderNo= InterfaceVer.VerStr(map.get("orderNo"));
            if(!orderNo.equals("")){
                order=orderMapper.selectByOrderNo(orderNo);
                if(order!=null){
                    String orderStatus=order.getOrderStatus()==null?"":order.getOrderStatus();
                    int userNoIdOrder=order.getUsernoId()==null?-1:order.getUsernoId();
                    if(userNoIdOrder!=userNoId){
                        return new Response(MessageConstants.MSG_CANCEL_ERROR,null,0,"取消失败,用户有误!",request);
                    }
                    if(!orderStatus.equals("701")){
                        return new Response(MessageConstants.MSG_CANCEL_ERROR,null,0,"取消失败,订单状态有误!",request);
                    }else {
                        order.setOrderStatus("706");
                        int res=orderMapper.updateByPrimaryKeySelective(order);
                        if(res>0) {
                            return new Response(MessageConstants.MSG_SUCCESS, 1, 1, "取消成功!", request);
                        }else {
                            return new Response(MessageConstants.MSG_CANCEL_ERROR,null,0,"取消失败!",request);
                        }
                    }
                }else {
                    return new Response(MessageConstants.MSG_CANCEL_ERROR,null,0,"取消失败!",request);
                }
            }else {
                return new Response(MessageConstants.MSG_CANCEL_ERROR,null,0,"取消失败!",request);
            }
        }else {
            return new Response(MessageConstants.MSG_CANCEL_ERROR,null,0,"取消失败!",request);
        }
    }

    @Transactional
    @Override
    public Response sureConfirm(Map<String, String> map, HttpServletRequest request) throws Exception {
        int userNoId=0;
        String orderNo="";
        Order order=new Order();
        if(map!=null) {
            userNoId = InterfaceVer.VerNumber(map.get("userNoId"));
            orderNo= InterfaceVer.VerStr(map.get("orderNo"));
            if(!orderNo.equals("")){
                order=orderMapper.selectByOrderNo(orderNo);
                if(order!=null){
                    String orderStatus=order.getOrderStatus()==null?"":order.getOrderStatus();
                    int userNoIdOrder=order.getUsernoId()==null?-1:order.getUsernoId();
                    if(userNoIdOrder!=userNoId){
                        return new Response(MessageConstants.MSG_SURE_ERROR,null,0,"确认收货失败,用户有误!",request);
                    }
                    if(!orderStatus.equals("703")){
                        return new Response(MessageConstants.MSG_SURE_ERROR,null,0,"确认收货失败,订单状态有误!",request);
                    }else {
                        order.setOrderStatus("705");
                        order.setPayFinishTime(new Date());
                        int res=orderMapper.updateByPrimaryKeySelective(order);
                        if(res>0) {
                            return new Response(MessageConstants.MSG_SUCCESS, 1, 1, "确认收货成功!", request);
                        }else {
                            return new Response(MessageConstants.MSG_SURE_ERROR,null,0,"确认收货失败!",request);
                        }
                    }
                }else {
                    return new Response(MessageConstants.MSG_SURE_ERROR,null,0,"确认收货失败!",request);
                }
            }else {
                return new Response(MessageConstants.MSG_SURE_ERROR,null,0,"确认收货失败!",request);
            }
        }else {
            return new Response(MessageConstants.MSG_SURE_ERROR,null,0,"确认收货失败!",request);
        }
    }

    @Override
    public List<Order> selectByOrderStatus(Order record) {
        return orderMapper.selectByOrderStatus(record);
    }

    @Override
    public List<Order> selectByOrderStatus1(Order record) {
        return orderMapper.selectByOrderStatus1(record);
    }

    @Override
    public List<Order> selectCancelOrder28(Order record) {
        return orderMapper.selectCancelOrder28(record);
    }

    @Override
    public int upAutoReceivingGoods(Date payFinishTime, List<String> orderNoList,String orderStatus) {
        return orderMapper.upAutoReceivingGoods(payFinishTime,orderNoList,orderStatus);
    }

    @Override
    public int upAutoCancalOrder(Date cancelTime, List<String> orderNoList, String orderStatus) {
        return orderMapper.upAutoCancalOrder(cancelTime,orderNoList,orderStatus);
    }

    @Override
    public int upOrderFrom(Date orderFromTime, List<String> orderNoList) {
        return orderMapper.upOrderFrom(orderFromTime,orderNoList);
    }

    @Override
    public List<Order> selectOrderCheck(Date ptime) {
        return orderMapper.selectOrderCheck(ptime);
    }

    @Transactional
    @Override
    public Response adminAddOrder(Map<String, String> map, HttpServletRequest request) throws Exception {
        Order order=new Order();
        String cartsTemp="";
        List<String> cartidsList=new ArrayList<>();
        Integer addressId=0;
        Double coupon=0.00;
        Double cashcoupon=0.00;
        Double freight=0.00;
        int userNoId = 0;
        int type=0;
        List<CartList> cartListList=new ArrayList<>();
        double orderMoney=0;
        double avgCoupon=0;
        double avgCashCoupon=0;

        int activity=0;
        int sumLimit=0;
        int monthLimit28=0;
        int provinceId=0;
        int supplierNoId=-1;
        int sumType=0;
        int oneType=0;
        double buyonePrice=0;
        double groupByPrice=0;
        String groupType="0";
        double groupPrice=0;
        int groupBuyGoodsId=0;
        int groupbuyId=0;
        String sInfo="";
        List<String> pList=new ArrayList<>();
        Set<String> hashSet=new HashSet<>();
        List<Spec> specList=new ArrayList<>();
        String resCartId="";
        int AID=0;
        int logType=0;
        String submitter="";
        String orderRemark="";
        int productId=0;
        int guigeId=0;
        int productCount=0;
        Set<String> hast=new HashSet<>();
        if(map!=null){
            submitter= InterfaceVer.VerStr(map.get("submitter"));
            orderRemark= InterfaceVer.VerStr(map.get("orderRemark"));
            AID= InterfaceVer.VerNumber(map.get("AID"));
            sInfo=map.get("sInfo")==null?"":map.get("sInfo");//产品信息
            if(!sInfo.equals("")){
                //System.out.println("sInfo:"+sInfo);
                JSONArray jsonArray=JSONArray.fromObject(sInfo);
                specList = (List<Spec>) JSONArray.toCollection(jsonArray, Spec.class);
                int ii=0;
                List<Spec> specListTT=new ArrayList<>();
                for (Spec spec:specList) {
                    int a=spec.getpCount()==null?0:spec.getpCount();
                    int b=spec.getId()==null?0:spec.getId();
                    int c=spec.getGoodsId()==null?0:spec.getGoodsId();
                    if(!hast.contains(a+b+c+"")){
                        specListTT.add(spec);
                    }
                    hast.add(a+b+c+"");
                }
                specList=specListTT;
                for (Spec spec:specList) {
                    productCount=spec.getpCount()==null?0:spec.getpCount();
                    guigeId=spec.getId()==null?0:spec.getId();
                    productId=spec.getGoodsId()==null?0:spec.getGoodsId();
                    Map<String,String> map1=new HashMap<>();
                    map1.put("userNoId",AID+"");
                    map1.put("productCount",productCount+"");
                    map1.put("productId",productId+"");
                    map1.put("guigeId",guigeId+"");
                    map1.put("shopId","1");
                    map1.put("groupType","1");
                    int res=cartService.addCart(map1,request);
                    if(res<=0){
                        throw new RuntimeException();
                    }else {
                        if(ii==specList.size()-1){
                            resCartId +=res;
                        }else {
                            resCartId +=res+",";
                        }
                    }
                    ii=ii+1;
                }
            }
            if(!resCartId.equals("")){
                cartidsList=JSON.parseArray("["+resCartId+"]",String.class);
            }
            userNoId = AID;
            //地址相关判断
            OrderAddress orderAddress = new OrderAddress();
                orderAddress.setProvinceId(InterfaceVer.VerNumber(map.get("provinceId")));
                orderAddress.setCityId(InterfaceVer.VerNumber(map.get("cityId")));
                orderAddress.setUserNoId(userNoId);
                orderAddress.setAreaId(InterfaceVer.VerNumber(map.get("areaId")));
                orderAddress.setName(InterfaceVer.VerStr(map.get("logName")));
                orderAddress.setPhone(InterfaceVer.VerStr(map.get("phone")));
                orderAddress.setDetailAddr(InterfaceVer.VerStr(map.get("detailAddr")));
                orderAddress.setIsDelete(0);
            if((orderAddress.getPhone()==null?"":orderAddress.getPhone()).equals("")){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"失败,手机号有误!",request);
            }
            if((orderAddress.getName()==null?"":orderAddress.getName()).equals("")){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"失败,收货姓名有误!",request);
            }
            if((orderAddress.getDetailAddr()==null?"":orderAddress.getDetailAddr()).equals("")){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"失败,详细地址有误!",request);
            }
            int orderAddressId=0,reso1=0;
            if(orderAddress!=null&&(orderAddress.getUserNoId()==null?0:orderAddress.getUserNoId())>0) {
                reso1 = orderAddressMapper.insert(orderAddress);
            }
            if (reso1 > 0) {
                orderAddressId=orderAddress.getId();
            }
            if(orderAddressId<=0){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"订单生成失败,地址不正确!",request);
            }
            //地址相关判断结束

            if(cartidsList!=null&&cartidsList.size()>0){
                cartListList=cartMapper.selectCartListSureOrder(userNoId,cartidsList);
                if(cartListList!=null&&cartListList.size()>0){
                    for (CartList cartList:cartListList) {
                        for (Carts carts:cartList.getCartsList()) {
                            guigeId=carts.getGuigeId()==null?0:carts.getGuigeId();//规格ID
                            supplierNoId=carts.getSupplierNoId()==null?-1:carts.getSupplierNoId();
                            LimitArea limitArea=limitAreaMapper.selectBySupplierId(supplierNoId);
                            if(limitArea!=null) {
                                String limitAreas = limitArea.getLimitAreas() == null ? "" : limitArea.getLimitAreas();
                                String guigeName = carts.getGuigeName() == null ? "" : carts.getGuigeName();
                                if (checkArea(provinceId + "", limitAreas)) {
                                    return new Response(MessageConstants.MSG_ADD_FAILED, null, 0, "失败,该产品" + guigeName + "当前地址不发货!", request);
                                }
                            }

                            productCount=carts.getProductCount()==null?0:carts.getProductCount();
                            int cartStatus=carts.getCartStatus()==null?501:carts.getCartStatus();
                            if(cartStatus==501) {
                                orderMoney += (carts.getPrice() == null ? 0 : carts.getPrice()) * productCount;
                                avgCoupon += (carts.getCoupon() == null ? 0 : carts.getCoupon()) * productCount;
                                avgCashCoupon += (carts.getVouchers() == null ? 0 : carts.getVouchers()) * productCount;
                            }else {
                                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"购物车已经生成!",request);
                            }
                        }
                    }
                }else{
                    return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"购物车已经生成",request);
                }
            }else {
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"购物车数据有误!",request);
            }
            if(orderMoney<=0){
                return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"生成失败,商品金额数据有误!",request);
            }

            order.setAddressId(orderAddressId);//地址id
            java.text.DateFormat format2 = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
            String orderString = format2.format(new Date());
            int intRandom=(int)(1+Math.random()*(10-1+1)*1000);
            String OrderNo="DA"+orderString+intRandom;
            order.setOrderNo(OrderNo);
            order.setOrderMoney(orderMoney);
            order.setAvaCoupon(avgCoupon);
            order.setAvaCashcoupon(avgCashCoupon);
//            order.setUsernoId(userNoId);
            order.setOrderAdminid(userNoId);
            order.setCoupon(coupon);
            order.setCashCoupon(cashcoupon);
            order.setFreight(freight);
            order.setGroupbuyGoodsid(groupBuyGoodsId);
            order.setGroupbuyId(groupbuyId);
            order.setOrderSubmitter(submitter+"");
            order.setOrderRemark(orderRemark);
            order.setOrderStatus("702");
            order.setPayTime(new Date());
            order.setInter(orderMoney);
            order.setRealPay(orderMoney);
            int res=orderMapper.insertSelective(order);
            if(res>0){
                Integer res1=cartMapper.upCartStatus(OrderNo,cartidsList);//更新购物车的状态
                if(res1>=0) {
                    if(type==1) {
//                        sumLimit=sumLimit-1;
//                        redisTemplate.opsForValue().set("sumLimit" + guigeId, sumLimit);
//                        redisTemplate.opsForValue().set("oneLimit" + userNoId + activity, productCount);
                        //28抢购 每个月只能抢购一个产品且购买数量只能为1
                        redisTemplate.opsForValue().set("monthLimit" + userNoId, 1);
                        //店主以下会员免费抢购只能抢两次
                        Object monthLimitAll = redisTemplate.opsForValue().get("monthLimitAll" + userNoId);
                        int monthLimitAllInt = InterfaceVer.VerNumber(monthLimitAll == null ? "0" : (int) monthLimitAll + "");
                        int lastNumber = monthLimitAllInt + 1;
                        redisTemplate.opsForValue().set("monthLimitAll" + userNoId, lastNumber);
                    }
                    if(oneType==1){
                        redisTemplate.opsForValue().set("oneLimit" + userNoId + activity, productCount);
                    }
                    if(sumType==1){
                        sumLimit=sumLimit-1;
                        redisTemplate.opsForValue().set("sumLimit" + guigeId, sumLimit);
                    }
                    return new Response(MessageConstants.MSG_SUCCESS, order.getOrderNo(), 1, "订单生成支付成功!", request);
                }else {
                    throw new RuntimeException();
                }
            }else {
                throw new RuntimeException();
                //return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"订单生成失败!",request);
            }
        }
        return new Response(MessageConstants.MSG_ADD_FAILED,null,0,"订单生成失败!",request);
    }


}
